/**
 * 
 */
package com.hcmu.view.MainHome;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.crypto.spec.PSource;

import vanhoc.android.utils.AlertDialogManager;

import com.telpoo.truyencuoi.R;
import com.hcmu.dto.DatabaseHelper;
import com.hcmu.dto.StoryDTO;
import com.hcmu.dto.CategoryDTO;
import com.hcmu.view.custome.CategoryAdapter;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.markupartist.android.widget.ActionBar.IntentAction;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.http.SslCertificate.DName;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author SEVEN
 *
 */
public class CreateNewStory extends Activity {
	private View app;
	DatabaseHelper dbHelper;
	Button btnAdd;
	ImageButton btnCustome;
	EditText txtStoryTitle, txtStoryContent, txtCategoryTitle;
	Spinner spinnerStoryType;
	int story_id = 0;
	private final static String TAG_ID = "id";
	private final static String TAG_TITLE = "title";
	private final static String TAG_TYPE = "type_id";
	ArrayList<CategoryDTO> categories;
	//Luu thong tin cua story trong truonghop update
	HashMap<String, String> story;
	ActionBar actionBar;
	Boolean isShowCategoryEditText = false;
	int cat_id;
	String storyTitle;
	String storyContent;
	String catTitleString;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = LayoutInflater.from(this);
        app = inflater.inflate(R.layout.layout_create_new_story, null);
        setContentView(app);
        
        dbHelper = new DatabaseHelper(this);
        bindComponents();
        initspinnerForTypeStory();
		showComponents();
        setListeners();
	}

	
	private void setListeners() {
		btnCustome.setOnClickListener(customeListener);
		btnAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//new CreateNewTask().execute();
				
				storyTitle = txtStoryTitle.getText().toString();
				storyContent = txtStoryContent.getText().toString();
				
				if (storyTitle.equals(null) || storyTitle.equals("")) {
					AlertDialogManager.showAlertDialog(CreateNewStory.this, "Error", "Please enter title", false);
				}else if (storyContent.equals(null) || storyContent.equals("")) {
					AlertDialogManager.showAlertDialog(CreateNewStory.this, "Error", "Please enter content", false);
				}else{
					if (isShowCategoryEditText == true) { // add/update 1 truyen voi category dc tao moi
						catTitleString = txtCategoryTitle.getText().toString();
						if (catTitleString.equals(null) || catTitleString.equals("")) {
							AlertDialogManager.showAlertDialog(CreateNewStory.this, "Error", "Please enter category", false);
						}else{
							//process
							//insert new record into types. then update type_id value of the story which is updated
							dbHelper.openToWrite();
							cat_id = (int) dbHelper.insertCategory(catTitleString);
							dbHelper.close();
							new CreateNewTask().execute();
						}
					}else{ //add/ update vao 1 category da ton tai (spinner)
						cat_id = categories.get(spinnerStoryType.getSelectedItemPosition()).getId();
						new CreateNewTask().execute();
					}
				}
			}
		});
	}

	
	private OnClickListener customeListener = new OnClickListener() {
		public void onClick(View v) {
			if (isShowCategoryEditText == false) { //dang an
				//show EditText
				txtCategoryTitle.setVisibility(View.VISIBLE);
				//an spinner
				spinnerStoryType.setVisibility(View.GONE);
				//thay doi icon cua nut
				btnCustome.setBackgroundResource(R.drawable.remove_icon);
				isShowCategoryEditText = true;
			}else{
				txtCategoryTitle.setVisibility(View.GONE);
				spinnerStoryType.setVisibility(View.VISIBLE);
				//thay doi icon cua nut
				btnCustome.setBackgroundResource(R.drawable.add_icon);
				isShowCategoryEditText = false;
			}
		};
	};
	
	
	
	private void showComponents() {
		//get Intent 
		Bundle extra = getIntent().getExtras();
		if (extra != null) story_id = extra.getInt("ID");
		if (story_id != 0) { //update
			actionBar.setTitle(getResources().getString(R.string.UPDATE_STORY));
			btnAdd.setText(getResources().getString(R.string.COMPLETE));
			//lay ve data  cua story 
			dbHelper.openToRead();
			story = dbHelper.getStory(story_id);
			dbHelper.close();
			
			//dua du lieu cu len cac edittext
			txtStoryTitle.setText(story.get("TITLE").toString());
			txtStoryContent.setText(story.get("CONTENT").toString());
			cat_id = Integer.parseInt(story.get("CAT_ID"));
			//lay ve vi tri cua  item trong spinner co id = type_id de dat dung item selected len spinner 
			spinnerStoryType.setSelection(getPosition(cat_id));
		}else{//add new
			btnAdd.setText(getResources().getString(R.string.ADD_NEW));
			actionBar.setTitle(getResources().getString(R.string.ADD_NEW_STORY));
		}
	}


	private void initspinnerForTypeStory() {
		categories = getStoryCategory();
		spinnerStoryType.setAdapter(new CategoryAdapter(this, R.layout.simple_text, categories));
	}


	private void bindComponents() {
		actionBar = (ActionBar) app.findViewById(R.id.actionbar);
		txtStoryTitle 		= (EditText) app.findViewById(R.id.txt_story_title);
		txtStoryContent 	= (EditText) app.findViewById(R.id.txt_story_content);
		spinnerStoryType 	= (Spinner) app.findViewById(R.id.spinner_type_story);
		btnAdd 				= (Button) app.findViewById(R.id.add_new_story);
		btnCustome 			= (ImageButton) app.findViewById(R.id.btnCustome);
		btnCustome.setBackgroundResource(R.drawable.add_icon);
		txtCategoryTitle 			= (EditText) app.findViewById(R.id.txtCategoryTitle);
	}


	/**
	 * Lay ve vi tri cua 1 loai truyen khi biet id cua no 
	 * @param typeid
	 * @return position
	 */
	private int getPosition(int typeid){
		for (int i = 0; i < categories.size(); i++) {
			if (categories.get(i).getId() == typeid) {
				return i;
			}
		}
		return 0;
	}
	

	private ArrayList<CategoryDTO> getStoryCategory(){
		ArrayList<CategoryDTO> list = new ArrayList<CategoryDTO>();
		dbHelper.openToRead();
		Cursor cursor = dbHelper.getAllCategory();
		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {
			CategoryDTO dto = new CategoryDTO();
			dto.setId(Integer.parseInt(cursor.getString(0)));
			dto.setTitle(cursor.getString(1).toString());
			list.add(dto);
			cursor.moveToNext();
		}
		dbHelper.close();
		
		return list;
	}
	
	
	
	
	public class CreateNewTask extends AsyncTask<Void, Void, Void>{
		private ProgressDialog dialog;
		
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			 dialog = ProgressDialog.show(CreateNewStory.this, "", "processing...");
		}
		
		
		
		@Override
		protected Void doInBackground(Void... params) {
			//Neu co story_id -> update
			dbHelper.openToWrite();
			if (story_id != 0) { //update
				dbHelper.updateStory(story_id, cat_id, storyTitle, storyContent);
			}else{//add
				dbHelper.insertStory(cat_id, storyTitle, storyContent, false, 0, 0, 0);
			}
			dbHelper.close();
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			if(dialog.isShowing()){
 			   dialog.dismiss();
 		   	}
			
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.SUCCESSFULLY), Toast.LENGTH_LONG).show();
			startActivity(new Intent(CreateNewStory.this, OfflineMainView.class));
		}
		
	}
	
}
